//
//  DHNewsDetailController.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/5/28.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHNewsDetailController.h"
#import "DHNewsDetailCoverCell.h"
#import "DHNewsDetail_WebCell.h"
#import "DHNewsDetail_CommentCell.h"
#import "DHNewsDetail_RecomendCell.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>

@interface DHNewsDetailController ()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) NSString *articleID;
@property (strong, nonatomic) NSDictionary *article;
@property (strong, nonatomic) NSArray *hotCommentsArray;    //最热评论
@property (strong, nonatomic) NSArray *latestCommentsArray; //最新评论
@property (strong, nonatomic) NSArray *relatedProductArray; //关联商品

@property (assign, nonatomic) NSNumber *webHeight; //网页加载后高度

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation DHNewsDetailController

- (instancetype)initWithArticleID:(NSString *)articleID
{
    self = [super init];
    if (self) {
        self.articleID = articleID;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text = @"资讯文章";
    
    UIButton *shareButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 54, self.navView.height - 44, 44, 44)];
    [shareButton setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    WeakSelf(weakSelf)
    [shareButton bk_addEventHandler:^(id sender) {
        [weakSelf shareNews];
    } forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:shareButton];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DHNewsDetailCoverCell" bundle:nil] forCellReuseIdentifier:kDHNewsDetailCoverCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHNewsDetail_WebCell" bundle:nil] forCellReuseIdentifier:kDHNewsDetail_WebCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHNewsDetail_CommentCell" bundle:nil] forCellReuseIdentifier:kDHNewsDetail_CommentCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHNewsDetail_RecomendCell" bundle:nil] forCellReuseIdentifier:kDHNewsDetail_RecomendCell];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    if (!self.isDianping) {
        [self loadDetailData];
    }
    
    [self loadCommentData];
    [self loadRecomendProduct];
}

- (void)dealloc
{
    NSLog(@"销毁");
}

- (void)shareNews{
    
    NSArray* imageArray = @[[self.article objectForKey:@"cover"]];

    if (imageArray) {
        NSString *url = [NSString stringWithFormat:@"%@share?article=%@",kHost,[self.article objectForKey:@"_id"]];
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:[self.article objectForKey:@"summary"]
                                         images:imageArray
                                            url:[NSURL URLWithString:url]
                                          title:[self.article objectForKey:@"title"]
                                           type:SSDKContentTypeAuto];
        [ShareSDK showShareActionSheet:nil customItems:nil shareParams:shareParams sheetConfiguration:nil onStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
            switch (state) {
                case SSDKResponseStateSuccess:
                {
                    [NSObject showHudTipStr:@"分享成功"];
                    break;
                }
                case SSDKResponseStateFail:
                {
                    [NSObject showHudTipStr:@"分享失败"];
                    break;
                }
                default:
                    break;
            }
        }];
    }
}

- (void)loadDetailData{
//    WeakSelf(weakSelf)
    [[DHNetAPIClient shareDHNetAPIClient] request_articlesDetailWithArticleID:self.articleID andBlock:^(id data, NSError *error) {
        self.article = [data objectForKey:@"article"];
        self.titleLabel.text =[self.article objectForKey:@"title"];
        [self.tableView reloadData];
    }];
}

- (void)loadCommentData{
//    WeakSelf(weakSelf)
    [[DHNetAPIClient shareDHNetAPIClient] request_articles_comments_simpleWithParams:@{@"_id":self.articleID} andBlock:^(id data, NSError *error) {
        
        self.hotCommentsArray = [data objectForKey:@"hotest"];
        self.latestCommentsArray = [data objectForKey:@"newest"];
        [self.tableView reloadData];
    }];
}

//获取推荐服饰
- (void)loadRecomendProduct{
//    WeakSelf(weakSelf)
    [[DHNetAPIClient shareDHNetAPIClient] request_products_related_witharticleWithParams:@{@"article_id":self.articleID} andBlock:^(id data, NSError *error) {
        if (data) {
            self.relatedProductArray = [data objectForKey:@"related"];
            [self.tableView reloadData];
        }
    }];
}

#pragma mark - UITableViewDelegate and UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 280;
    }else if (indexPath.row == 1){
        if (self.webHeight.floatValue > 0) {
            return self.webHeight.floatValue + 60;
        }else{
            return 100;
        }
    }else if (indexPath.row == 2){
        if (self.hotCommentsArray.count > 0) {
            return self.hotCommentsArray.count * 147 + 40;
        }else{
            return 40 + 40;
        }
    }else if (indexPath.row == 3){
        if (self.latestCommentsArray.count > 0) {
            return self.latestCommentsArray.count * 147 + 40;
        }else{
            return 40 + 40;
        }
    }else if (indexPath.row == 4){
        return (self.relatedProductArray.count / 2) * 280 + 30;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        DHNewsDetailCoverCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHNewsDetailCoverCell forIndexPath:indexPath];
        if (self.isDianping) {
//            NSArray *images = [self.dianpingDic objectForKey:@"images"];
//            if (images.count > 0) {
//                [cell.coverImageView dh_setImageURLString:[images objectAtIndex:0]];
//            }else{
//                [cell.coverImageView setImage:[UIImage imageNamed:@"img_default.jpg"]];
//            }
//            cell.titleLabel.text = [dic objectForKey:@"title"];
//            self.nameLabel.text = [[dic objectForKey:@"owner"] objectForKey:@"nickname"];
//            NSDate *date = [NSDate dateWithServerISOString:[dic objectForKey:@"createdAt"] format:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
//            self.timeLabel.text = [NSDate stringFromDate:date withFormat:@"yyyy/MM/dd HH:mm"];
//            self.commentLabel.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"comments_count"]];
//            self.likeLabel.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"collected_count"]];
//            [self.headerImgView dh_setImageURLString:[[dic objectForKey:@"owner"] objectForKey:@"photo"]];
        }else{
            [cell updateCell:self.article];
        }
        return cell;
    }else if (indexPath.row == 1){
        DHNewsDetail_WebCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHNewsDetail_WebCell forIndexPath:indexPath];
        [cell updateCell:self.article];
        return cell;
    }else if (indexPath.row == 2){
        DHNewsDetail_CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHNewsDetail_CommentCell forIndexPath:indexPath];
        cell.titleLabel.text = @"热门评论";
        cell.allView.hidden = YES;
        [cell updateCellArr:self.hotCommentsArray];
        return cell;
    }else if (indexPath.row == 3){
        DHNewsDetail_CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHNewsDetail_CommentCell forIndexPath:indexPath];
        cell.titleLabel.text = @"最新评论";
        cell.allView.hidden = NO;
        cell.articleID = self.articleID;
        [cell updateCellArr:self.latestCommentsArray];
        return cell;
    }else if (indexPath.row == 4){
        DHNewsDetail_RecomendCell *cell = [tableView dequeueReusableCellWithIdentifier:kDHNewsDetail_RecomendCell forIndexPath:indexPath];
        [cell updateCellArr:self.relatedProductArray];
        return cell;
    }else{
        return nil;
    }
}

- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    if ([eventName isEqualToString:@"webViewDidFinishLoad"]) {
        self.webHeight = [userInfo objectForKey:@"height"];
        [self.tableView beginUpdates];
        [self.tableView endUpdates];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 数组初始化
- (NSArray *)hotCommentsArray{
    if (!_hotCommentsArray) {
        _hotCommentsArray = [NSArray array];
    }
    return _hotCommentsArray;
}

- (NSArray *)latestCommentsArray{
    if (!_latestCommentsArray) {
        _latestCommentsArray = [NSArray array];
    }
    return _latestCommentsArray;
}

- (NSArray *)relatedProductArray{
    if (!_relatedProductArray) {
        _relatedProductArray = [NSArray array];
    }
    return _relatedProductArray;
}

@end
